package com.hmdp.utils;

import cn.hutool.core.io.resource.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘宇
 */
public class SimpleRedisLock implements ILock {

    //锁名称
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    //key前缀
    private static final String KEY_PREFIX = "lock:";
    //ID前缀
    private static final String ID_PREFIX = UUID.randomUUID().toString()+"-";

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /*
     * 加载Lua脚本
     */
    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    /**
     * 获取锁
     * @param timeoutSec 设置超时时间
     * @return 返回获取结果
     */
    @Override
    public boolean tryLock(long timeoutSec) {
        //线程表示
        String threadId =ID_PREFIX+ Thread.currentThread().getId();
        //获取锁
        String key = KEY_PREFIX+name;
        Boolean success = stringRedisTemplate
                .opsForValue().setIfAbsent(key, threadId, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(success);
    }

    /**
     * 释放锁
     */
    @Override
    public void unlock(){
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());
    }
//    @Override
//    public void unlock() {
//        //获取标识
//        String threadId =ID_PREFIX+ Thread.currentThread().getId();
//        //判断标识是否一致
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX+name);
//        if(threadId.equals(id)) {
//            //释放锁
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//    }
}
